package com.cyl.manager.act.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.h5.config.SecurityUtil;
import com.cyl.manager.act.constant.IntegralRule;
import com.cyl.manager.act.domain.entity.IntegralHistory;
import com.cyl.manager.act.domain.query.IntegralHistoryQuery;
import com.cyl.manager.act.domain.vo.IntegralStatVO;
import com.cyl.manager.act.mapper.IntegralHistoryMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.entity.MemberAccount;
import com.cyl.manager.ums.mapper.MemberAccountMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;

import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;

/**
 * 积分流水表Service业务层处理
 *
 * @author zcc
 */
@Service
@Slf4j
@Transactional
public class IntegralHistoryService {
    @Autowired
    private IntegralHistoryMapper integralHistoryMapper;
    @Autowired
    private MemberAccountMapper memberAccountMapper;
    @Autowired
    private ISysConfigService sysConfigService;
    
    
    @Autowired
    private MemberMapper memberMapper;
    

    /**
     * 查询积分流水表
     *
     * @param id 积分流水表主键
     * @return 积分流水表
     */
    public IntegralHistory selectById(Long id) {
        return integralHistoryMapper.selectById(id);
    }

    /**
     * 查询积分流水表列表
     *
     * @param query 查询条件
     * @param page  分页条件
     * @return 积分流水表
     */
    public List<IntegralHistory> selectList(IntegralHistoryQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<IntegralHistory> qw = new QueryWrapper<>();
        Long memberId = query.getMemberId();
        if (memberId != null) {
            qw.eq("member_id", memberId);
        }
        BigDecimal amount = query.getAmount();
        if (amount != null) {
            qw.eq("amount", amount);
        }
        Integer opType = query.getOpType();
        if (opType != null) {
            qw.eq("op_type", opType);
        }
        Integer subOpType = query.getSubOpType();
        if (subOpType != null) {
            qw.eq("sub_op_type", subOpType);
        }
        BigDecimal orderAmount = query.getOrderAmount();
        if (orderAmount != null) {
            qw.eq("order_amount", orderAmount);
        }
        Long orderId = query.getOrderId();
        if (orderId != null) {
            qw.eq("order_id", orderId);
        }
        return integralHistoryMapper.selectList(qw);
    }

    public List<IntegralHistory> selectList2(IntegralHistoryQuery query) {
        QueryWrapper<IntegralHistory> qw = new QueryWrapper<>();
        Long memberId = query.getMemberId();
        if (memberId != null) {
            qw.eq("member_id", memberId);
        }
        Integer opType = query.getOpType();
        if (opType != null) {
            qw.eq("op_type", opType);
        }
        Integer subOpType = query.getSubOpType();
        if (subOpType != null) {
            qw.eq("sub_op_type", subOpType);
        }
        if (query.getStart() != null) {
            qw.ge("create_time", query.getStart());
        }
        if (query.getEnd() != null) {
            qw.le("create_time", query.getEnd());
        }
        return integralHistoryMapper.selectList(qw);
    }

    /**
     * 新增积分流水表
     *
     * @param integralHistory 积分流水表
     * @return 结果
     */
    public int insert(IntegralHistory integralHistory) {
        integralHistory.setCreateTime(LocalDateTime.now()); 
        return insert2(integralHistory);
    }

     // 11签到  12消费获得  21退款扣除积分  13后台添加店长积分 14 后台扣减店长积分    16店长扣减会员积分      
    public int insert2(IntegralHistory history) {
        Long memberId = history.getMemberId();
        Member member =  memberMapper.selectById(memberId);
        history.setDeptDpId(member.getDeptDpId());
        history.setSpreaduid(member.getSpreaduid());
        history.setDeptTzId(member.getDeptTzId());
        history.setDeptZbjId(member.getDeptZbjId());
        //保存member_account
        MemberAccount memberAccount = memberAccountMapper.selectById(memberId);
        if (memberAccount == null) {
            memberAccount = new MemberAccount();
            memberAccount.setMemberId(memberId);
            memberAccount.setIntegralBalance(history.getAmount());
            memberAccount.setTotalIntegralBalance(history.getAmount());
            memberAccount.setCreateTime(LocalDateTime.now());
            
            
        	if(new BigDecimal("0.00").add(history.getAmount()).signum() < 0) {
                throw new RuntimeException("扣除后积分不能小于0！当前积分：0");
        	}
        	
            memberAccountMapper.insert(memberAccount);
        } else {
        	 
        	if(memberAccount.getIntegralBalance().add(history.getAmount()).signum() < 0) {
                throw new RuntimeException("扣除后积分不能小于0！当前积分："+memberAccount.getIntegralBalance().toString());
        	}
            memberAccountMapper.updateIntegralBalance(history.getAmount(), memberId);
        }
        return integralHistoryMapper.insert(history);
    }
   
    public void handleIntegral(Long orderId, BigDecimal amount, Long memberId) {
        String config = sysConfigService.selectConfigByKey(Constants.INTEGRAL_RULE_KEY);
        IntegralRule rule;
        if (StringUtils.isNotEmpty(config)) {
            rule = JSON.parseObject(config, IntegralRule.class);
        } else {
            rule = new IntegralRule();
        }
        BigDecimal divide = amount;// amount.divide(rule.getOrderAmount(), 0, RoundingMode.DOWN);
        if (divide.compareTo(BigDecimal.ZERO) < 1) {
            log.info("订单：{}，金额：{}不足{}元，不记录积分",orderId,amount,rule.getOrderAmount());
            return;
        }
        BigDecimal total = divide.multiply(rule.getOrderCount());
        if (total.compareTo(BigDecimal.ZERO) < 1) {
            log.info("订单：{}，orderCount为0，不记录积分",orderId);
            return;
        }
        IntegralHistory history = new IntegralHistory();
        history.setOpType(1);
        history.setSubOpType(12);
        history.setAmount(total);
        history.setOrderId(orderId);
        history.setOrderAmount(amount);
        history.setMemberId(memberId);
        history.setBz("订单编号： "+orderId + " 消费获得积分");
        history.setCreateTime(LocalDateTime.now());
        insert2(history);
    }
    
    @Transactional
    public int handleIntegralMain(int subOpType, BigDecimal amount, Long memberId, Long dpMemberId,String bz) {
    	handleIntegralBase(subOpType, amount, memberId, dpMemberId, bz,null);
		if(subOpType == 15) {
			handleIntegralBase(17, amount, dpMemberId, null, "您给会员id为："+memberId+"，添加"+amount+"积分，扣减你的积分 "+bz,null);
		}
		return subOpType;
    }
    
    // 13后台添加  14 后台扣减  15店长添加   16店长扣减  17店长给会员加积分扣减自己积分  18 积分商城
    public int handleIntegralBase(int subOpType, BigDecimal amount, Long memberId, Long dpMemberId,String bz,Long orderId) {
    	if(bz==null) {
    		bz = "";
    	}
    	
    	if(subOpType == 18) {
        	bz = "积分商城兑换，扣减您"+amount+"积分 "+bz;
		}
    	if(subOpType == 13) {//13后台添加 
    		bz = "后台管理员id为："+SecurityUtils.getUserId()+"，为您添加"+amount+"积分 "+bz;
		}
    
    	if(subOpType == 14) {
    		bz = "后台管理员id为："+SecurityUtils.getUserId()+"，扣减您"+amount+"积分 "+bz;
		}
    	
    	if(subOpType == 15) {
    		bz = "店长id为："+dpMemberId+"，为您添加"+amount+"积分 "+bz;
		}
    	if(subOpType == 16) {
    		bz = "店长id为："+dpMemberId+"，扣减您"+amount+"积分 "+bz;
		}
    	
    	int opType = 0; //1：收入 2：支出  3：其他
    	if(subOpType == 13 || subOpType == 15) {
    		opType =1;
    	}
    	if(subOpType == 14 || subOpType == 16 || subOpType == 17 ||   subOpType == 18) {
    		opType =2;
    	    if (amount.compareTo(new BigDecimal("0.00")) > 0) {
    	    	amount = amount.negate();
    	    }
    		
    	}
    	if(opType == 0) {
            throw new RuntimeException("不支持的类型！"+subOpType);
    	}
        IntegralHistory history = new IntegralHistory();
        history.setOpType(opType);
        history.setSubOpType(subOpType);
        history.setAmount(amount);
        history.setMemberId(memberId);
        history.setOrderId(orderId);
        history.setCreateTime(LocalDateTime.now());
        history.setDpMemberId(dpMemberId);
        history.setBz(bz);
        return insert2(history);
    }
//    public static void main(String[] args) {
//    	BigDecimal amount = new BigDecimal("100.00");
//    	 if (amount.compareTo(new BigDecimal("0.00")) > 0) {
// 	    	amount = amount.negate();
// 	    }
//    	 System.out.println(amount);
//	}

    /**
     * 修改积分流水表
     *
     * @param integralHistory 积分流水表
     * @return 结果
     */
    public int update(IntegralHistory integralHistory) {
        return integralHistoryMapper.updateById(integralHistory);
    }

    /**
     * 删除积分流水表信息
     *
     * @param id 积分流水表主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return integralHistoryMapper.deleteById(id);
    }

    public List<IntegralHistory> selectListByH5(IntegralHistoryQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<IntegralHistory> qw = new QueryWrapper<>();
        qw.eq("member_id", SecurityUtil.getLocalMember().getId())
                .ge("create_time", query.getStart())
                .le("create_time", query.getEnd());
        Integer opType = query.getOpType();
        if (opType != null) {
            qw.eq("op_type", opType);
        }
        Integer subOpType = query.getSubOpType();
        if (subOpType != null) {
            qw.eq("sub_op_type", subOpType);
        }
        qw.orderByDesc("id");
        return integralHistoryMapper.selectList(qw);
    }

    public IntegralStatVO statIntegral(IntegralHistoryQuery query) {
        Long memberId = SecurityUtil.getLocalMember().getId();
        IntegralStatVO statVO = integralHistoryMapper.statIntegral(query.getStart(), query.getEnd(), memberId);
        if (statVO == null) {
            statVO = new IntegralStatVO();
        }
        MemberAccount memberAccount = memberAccountMapper.selectById(memberId);
        statVO.setBalance(memberAccount == null ? BigDecimal.ZERO : memberAccount.getIntegralBalance());
        return statVO;
    }
}
